import {
  Button,
  Card,
  Col,
  DatePicker,
  Input,
  message,
  Radio,
  Row,
  Select,
  Table,
  Spin,
  Tooltip,
  Icon,
} from "antd";
import { connect } from "dva";
import moment from "moment";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import styles from "./index.less";
import Ellipsis from "@/components/Ellipsis";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import TemplateCard from "@/support/components/TemplateCard";
import * as G from "@/utils/common";
import ExportTaskModal from "./exportTaskModal";
import PateoAuthButtons from "@/common/PateoAuthButtons/PateoAuthButtons";
import FieldModal from "./fieldModal";
import Password from "antd/lib/input/Password";
import SearchAdtional from "../creditCar/component/searchAdtional/index";
import data from "./data";
import enums from "../creditCar/enums";
import RiskStatusModal from "../creditCar/riskStatusModal";
import { Form } from '@ant-design/compatible';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import { SettingOutlined } from '@ant-design/icons';
import { transferOption } from "@/utils/common";
import { isArguments } from "lodash";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;

var now = new Date(); //当前日期
var nowDayOfWeek = now.getDay(); //今天本周的第几天
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowYear = now.getYear(); //当前年
nowYear += nowYear < 2000 ? 1900 : 0; //

//格式化日期：yyyyMMdd
function formatDate(date) {
  var myyear = date.getFullYear();
  var mymonth = date.getMonth() + 1;
  var myweekday = date.getDate();

  if (mymonth < 10) {
    mymonth = "0" + mymonth;
  }
  if (myweekday < 10) {
    myweekday = "0" + myweekday;
  }
  return myyear + "" + mymonth + "" + myweekday;
}
// 下划线转驼峰
function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}
@connect((state) => ({
  menu: state.menu,
  mileage: state.mileage,
  warningRecord: state.warningRecord,
  creditCar: state.creditCar,
}))
@Form.create()
export default class mileage extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.object,
  };
  state = {
    formValues: {
      businessCode: "mileage",
      startTime: formatDate(
        new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
      ), //本周开始日期
      endTime: formatDate(new Date(nowYear, nowMonth, nowDay)),
      totalPeriodType: 2,
    },
    // orgList: [], // 车辆所属公司列表
    dates: [],
    dateDisable: true, // 具体日期是否可以选择
    initFlag: false,
    pageObj: {
      current: 1,
      pageSize: 10,
    },
    tboxRouseloading: false,
    tboxRouseCount: 35,
    tableColumns: [], //动态列表clonmn数据源
    columns: [], // 真实columns
    fieldList: [],
    visible: false,
    checked: [],
    fieldMore: [], // 更多筛选可以使用的字段
    seriesList: [], //车系数据
    riskEventList: [],
    fieldColumns: [], // 更多筛选选择的条件
    filterTime: {}, // 更多筛选选择的统计周期
    currentSearchMode: "1", // 1: 外部搜索   2，更所筛选搜索

    riskStatusModalVisible: false,
    riskvin: undefined,
    orgList: [],
    creditTypeOptions: [],
  };

  componentDidMount() {
    this.getDic();
    this.handleGetOrgList();
    // this.handleFlushPage();
    this.getFieldList();
    this.handleGetSeriesByBrandCode();
    this.handleGetriskEventList();
    this.handleGetFieldList();
    this.handleFlushPage();
  }
  getDic = () =>{
    const {menu: { dicData }} = this.props;
    const typeOption = getDictOptionsByCode(dicData, 'creditType');
    this.setState({
      creditTypeOptions: typeOption.map(e => ({
            label: e.label,
            value: e.value,
          })),
   })
  }
  loop = (arr) => {
    let tree= JSON.parse(JSON.stringify(arr))
      let newData = []
    const expanded = datas => {
      if (datas&& datas.length > 0){
        datas.forEach(e => {
          newData.push({sid: e.sid, name: e.orgName});
          expanded(e.children);
        })
      }
    };
    expanded(tree);
    return newData;
  }
  handleGetOrgList = () => {
    this.props.dispatch({
      type: "mileage/getDataWithRes",
      payload: {
        url: "/org/tree",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            const newData =  this.loop(response.data)
            this.setState({
              orgList: newData,
            });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  // 获取车系数据方法
  handleGetSeriesByBrandCode = () => {
    this.props.dispatch({
      type: "mileage/getDataWithRes",
      payload: { url: '/msdevice/base/vehicle/series/list' },
      callback: (response) => {
        this.setState({
          seriesList: response.data.map(e => ({
            label: e.seriesName,
            value: e.seriesCode,
          })),
        });
      },
    });
  };
  handleGetriskEventList = () => {
    this.props.dispatch({
      type: "mileage/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/event/page", 
        ...{
          curPage: 1,
          pageSize: 1000,
          enable: enums.riskEventEnable.effective.value,
        },
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          this.setState({
            riskEventList: response.data.rows.map((i) => ({
              value: i.sid,
              label: i.riskEventContent,
            })),
          });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleGetFieldList = () => {
    this.props.dispatch({
      // 更多筛选数据
      type: "mileage/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=mileage&scene=more",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            this.setState({
              fieldMore: response.data,
            });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  //页面刷新方法
  handleFlushPage = (flag) => {
    // 获取列表数据
    const { dispatch } = this.props;
    if (flag) {
      const { formValues, pageObj } = this.state;
      const params = {
        businessCode: "mileage",
        startTime: formatDate(
          new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
        ), //本周开始日期
        endTime: formatDate(new Date(nowYear, nowMonth, nowDay)),
        curPage: 1,
        pageSize: 10,
      };
      dispatch({
        type: "mileage/queryList",
        payload: {
          url: "/mscreditbusiness/vehicle/mileage/report/page",
          ...params,
        },
        callback: (response) => {
          this.setState({ initFlag: true });
        },
      });
    } else {
      if (this.props.location && this.props.location.state) {
        const { formValues, pageObj } = this.props.location.state;
        if (formValues) {
          this.props.form.setFieldsValue({ ...formValues });
          this.setState({
            formValues,
            pageObj,
          });
        }
        dispatch({
          type: "mileage/queryList",
          payload: {
            url: "/mscreditbusiness/vehicle/mileage/report/page",
            ...formValues,
            curPage: pageObj.current,
            pageSize: pageObj.pageSize,
          },
          callback: (response) => {
            this.setState({ initFlag: true });
          },
        });
      } else {
        const { formValues, pageObj } = this.state;
        dispatch({
          type: "mileage/queryList",
          payload: {
            url: "/mscreditbusiness/vehicle/mileage/report/page",
            ...formValues,
            ...pageObj,
            totalPeriodType: 2,
          },
          callback: (response) => {
            this.setState({ initFlag: true });
          },
        });
      }
    }
  };
  onRef = (ref) => {
    this.Child = ref;
  };
  addPreinstall = (columns) => {
    return columns.map((i) => {
      const sameTitle = columns.some(
        (j) => j.name === i.name && i.fieldId !== j.fieldId
      );
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`;
      }
      return i;
    });
  };
  getFieldList = () => {
    // 获取列表字段
    this.props.dispatch({
      type: "mileage/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=mileage&scene=list",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            const fieldData = response.data;
            const arr = [];
            this.addPreinstall(response.data).map((item) => {
              if (item.type === 4) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text ? moment(text).format("YYYY-MM-DD") : "";
                    } else {
                      return text
                        ? moment(text, "YYYY-MM-DD").format("YYYY-MM-DD")
                        : "";
                    }
                  },
                });
              } else if (item.type === 5) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text ? moment(text).format("HH:mm:ss") : "";
                    } else {
                      return text
                        ? moment(text, "HH:mm:ss").format("HH:mm:ss")
                        : "";
                    }
                  },
                });
              } else if (item.type === 6) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text
                        ? moment(text).format("YYYY-MM-DD HH:mm:ss")
                        : "";
                    } else {
                      return text
                        ? moment(text, "YYYY-MM-DD HH:mm:ss").format(
                            "YYYY-MM-DD HH:mm:ss"
                          )
                        : "";
                    }
                  },
                });
              } else if (item.name === "是否支持跛行") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    return text == 1 ? "是" : "否";
                  },
                });
              } else if (item.name === "车辆预警状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == "0") {
                      return "未预警";
                    } else if (text == "1") {
                      return "预警";
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "还款状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == "0") {
                      return "还款中";
                    } else if (text == "1") {
                      return "已逾期";
                    } else if (text == "2") {
                      return "已结清";
                    } else if (text == "3") {
                      return "融资已到期";
                    } else {
                      return "未知";
                    }
                  },
                });
              } else if (item.name === "车辆风控状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text, record) => {
                    if (text == 0) {
                      return "正常行驶"; 
                    } else if (text == 1) {
                      return "锁车"; 
                    } else if (text == 2) {
                      return "跛行"; 
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "车机告警类型") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "暂不支持";
                    } else if (text == 1) {
                      return "不可配置";
                    } else if (text == 2) {
                      return "可配置";
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "车机告警状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "正常";
                    } else if (text == 1) {
                      return "车机告警";
                    } else if (text == 5) {
                      return "无";
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "实车当前状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "正常";
                    } else if (text == 1) {
                      return "锁车";
                    } else if (text == 2) {
                      return "跛行";
                    } else if (text == 3) {
                      return "待车辆反馈";
                    } else {
                      return "待车辆反馈";
                    }
                  },
                });
              } else if (item.name === "授信类型") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: text => {
                    if (text == null) {
                      return '';
                    }
                    return getDicByKey(this.context.dicData, `creditType`, text.toString());
                  },
                });
              }else {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                });
              }
            });
            const list = fieldData.map((item) => {
              return {
                label: item.name,
                value: item.column,
              };
            });
            const { checked, columns } = this.state;
            const { menu : { userProfile } } = this.props;
            if (columns.length === 0) {
               //如果设置过列表
              const data = JSON.parse(localStorage.getItem("creditData"));
              const id = `mileageColumns_${userProfile.merchant1Id}_${userProfile.accountName}`;
              let columns = null;
              if(data){
                columns = data[id];
              }
              if (columns) {
                const storedColumns = JSON.parse(columns); //存储的列表字段
                const new_columns = [];
                arr.map((i) => {
                  const _current = storedColumns.find(
                    (j) => j.dataIndex == i.dataIndex
                  );
                  if (_current) {
                    new_columns.push(i);
                  }
                });
                this.setState({
                  columns: new_columns,
                });
              } else {
                this.setState({
                  columns: arr,
                });
              }
            }
            if (checked.length === 0) {
              // 未设置过列表选择状态
              const data = JSON.parse(localStorage.getItem("creditData"));
              const id = `mileageChecked_${userProfile.merchant1Id}_${userProfile.accountName}`;
              let checkedforSession = null;
              if(data){
                checkedforSession = data[id];
              }
              if (checkedforSession) {
                this.setState({
                  checked: JSON.parse(checkedforSession),
                });
              } else {
                const checkeds = [];
                fieldData.forEach((e) => {
                  checkeds.push(e.column);
                });
                this.setState({
                  checked: checkeds,
                });
              }
              this.setState({
                fieldList: list,
                tableColumns: arr,
                // checked: checkeds
              });
            } else {
              this.setState({
                fieldList: list,
                tableColumns: arr,
              });
            }
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  openFieldModal = () => {
    this.getFieldList();
    this.setState({
      visible: true,
    });
  };
  // 列表显示字段筛选方法
  filterColumns = (checkedValue) => {
    const { tableColumns } = this.state;
    const { menu : { userProfile } } = this.props;
    const newColumns = [];
    console.log("选中要显示的列", checkedValue);
    console.log("目前的列", tableColumns);
    const value = [];
    checkedValue.forEach((e) => {
      value.push(toCamel(e));
    });
    tableColumns.map((item) => {
      if (value.includes(item.dataIndex)) {
        newColumns.push(item);
      }
    });
    const data = JSON.parse(localStorage.getItem("creditData"));
    const id1 = `mileageColumns_${userProfile.merchant1Id}_${userProfile.accountName}`;
    const id2 = `mileageChecked_${userProfile.merchant1Id}_${userProfile.accountName}`
   //首先进入页面需要先判断是否存在localData
   if (data) {
    data[id1] = JSON.stringify(newColumns);
    data[id2] = JSON.stringify(checkedValue);
   localStorage.setItem("creditData", JSON.stringify(data));
    }else{
     const creditData ={};
     creditData[id1] = JSON.stringify(newColumns);
     creditData[id2] = JSON.stringify(checkedValue);
     localStorage.setItem("creditData", JSON.stringify(creditData));
  }
    this.setState({
      columns: newColumns,
      tableColumns: newColumns,
      checked: checkedValue,
    });
  };
  specialDataGenrator = () => {
    const {dispatch, } = this.props;
    // 生成特殊字段
    return [
      {
        // 所属公司
        columnName: "vin",
        columnType: 1,
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        // 所属公司
        columnName: "company_name",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.orgList.map((i) => ({
            label: i.name,
            value: i.sid,
          })),
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        // 车系
        columnName: "series_name",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.seriesList,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        // filterTypeLock: true,
        // defaultField: true,
      },
      {
        columnName: "last7_mileage",
        columnType: 3,
        filter: undefined,
        startVal: undefined,
        endVal: undefined,
        filterType: "1",
      },
      {
        columnName: "risk_event_content",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.riskEventList.map((i) => ({
            value: i.sid,
            label: i.riskEventContent,
          })),
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "limp_enable",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "不支持",
            },
            {
              value: "1",
              label: "支持",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "warn_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "暂不支持",
            },
            {
              value: 1,
              label: "不可配置",
            },
            {
              value: 2,
              label: "可配置",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "车机告警",
            },
            {
              value: "5",
              label: "无",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "repayment_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 0-还款中；1-已逾期；2-已结清；3-融资已到期
              value: "0",
              label: "还款中",
            },
            {
              value: "1",
              label: "已逾期",
            },
            {
              value: "99",
              label: "未知",
            },
            {
              value: "2",
              label: "已结清",
              hideInOption: true,
            },
            {
              value: "3",
              label: "融资已到期",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "risk_warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 1：预警  0或null：未预警 ；
              value: "0",
              label: "未预警",
            },
            {
              value: "1",
              label: "预警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "engine_state",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //  2-点火；0-熄火
              value: "0",
              label: "熄火",
            },
            {
              value: "2",
              label: "点火",
            },
            {
              value: "",
              label: "行驶中",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "risk_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //   0-正常行驶，1-锁车，2-跛行
              value: "0",
              label: "正常行驶",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "credit_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.creditTypeOptions,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        // 实车当前状态
        columnName: "vhl_current_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "正常",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
            {
              value: "3",
              label: "待车辆反馈",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
    ];
  };

  exChangeDefaultData = () => {
    // 从外面带的属性
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      console.log("更多筛选条件", fieldsValue);
      return [
        {
          columnName: "vin",
          columnType: 1,
          filter: fieldsValue.vin ? "1" : undefined,
          startVal: fieldsValue.vin,
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "company_name",
          filter: fieldsValue.orgId ? "9" : undefined,
          startVal: fieldsValue.orgId,
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "risk_status",
          filter: fieldsValue.riskStatus ? "9" : undefined,
          startVal: fieldsValue.riskStatus,
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "credit_type",
          columnType: 2,
          filter: creditType ? "9" : undefined,
          startVal: fieldsValue.credit_type,
          endVal: undefined,
          filterType: "1",
        },
      ];
    });
  };
  // //更多筛选
  moreFilter = (e) => {
    if (e) {
      e.preventDefault();
    }
    const { form } = this.props;
    console.log('xxxx')
    form.validateFields((err, fieldsValue) => {
      setTimeout(() => {
      this.SearchAdtionalRef.setFiled(fieldsValue.totalPeriodType, fieldsValue.rangeTime)
     }, 10);
      console.log("更多筛选条件", fieldsValue); //从外面带进来的值
      const exChangeData = [
        {
          columnName: "vin",
          columnType: 1,
          filter: fieldsValue.vin ? "1" : undefined,
          startVal: fieldsValue.vin,
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "company_name",
          columnType: 2,
          filter: fieldsValue.orgId ? "9" : undefined,
          startVal: Number(fieldsValue.orgId),
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "risk_status",
          columnType: 2,
          filter:
            typeof fieldsValue.riskStatus !== "undefined" ? "9" : undefined,
          startVal: fieldsValue.riskStatus,
          endVal: undefined,
          filterType: "1",
        },
        {
          columnName: "credit_type",
          columnType: 2,
          filter: fieldsValue.creditType ? "9" : undefined,
          startVal: fieldsValue.creditType,
          endVal: undefined,
          filterType: "1",
        },

      ];
      this.SearchAdtionalRef.setStateData({
        dates: this.state.dates,
        dateDisable: this.state.dateDisable,
      });
      // this.SearchAdtionalRef.form.setFieldsValue({
      //   totalPeriodType: fieldsValue.totalPeriodType,
      //   rangeTime: fieldsValue.rangeTime,
      // });
      const specialData = this.specialDataGenrator(); // 特殊字段，本地定义
      console.log("exChangeData", exChangeData);
      console.log('specialData', specialData)
      this.SearchAdtionalRef.modalShow(specialData, exChangeData);
   
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      formValues: {
        businessCode: "mileage",
        startTime: formatDate(
          new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
        ), //本周开始日期
        endTime: formatDate(new Date(nowYear, nowMonth, nowDay)),
      },
      fieldColumns: [],
      filterTime: {},
      currentSearchMode: "1",
      // checked: []
    });
    this.handleFlushPage(true);
  };
  getStatisticalCycle = (value) => {
    //获取更多筛选中获取的统计周期
    console.log("tongjizhouqwi", value);
    this.setState({
      filterTime: value,
    });
  };
  handleSearchFor = () => {
    this.setState(
      {
        currentSearchMode: "1",
      },
      () => {
        this.handleSearch();
      }
    );
  };
  handleSearch = () => {
    const { dispatch, form } = this.props;
    const { formValues, pageObj, fieldColumns, filterTime, currentSearchMode } =
      this.state;
      console.log('更多筛选的condition',fieldColumns)
      console.log('currentSearchMode', currentSearchMode)
      console.log('filterTime', filterTime)
    form.validateFields((err, fieldsValue) => {
      console.log('更多筛选的值', fieldsValue)
      if (err) return;
      if (currentSearchMode == "1") {
        //非更多筛选
        if (fieldsValue.rangeTime) {
          fieldsValue.startTime = moment(fieldsValue.rangeTime[0]).format(
            "YYYYMMDD"
          );
          fieldsValue.endTime = moment(fieldsValue.rangeTime[1]).format(
            "YYYYMMDD"
          );
          delete fieldsValue.rangeTime;
          // delete fieldsValue.totalPeriodType;
        }
        if (fieldsValue.totalPeriodType === 2) {
          //本周
          fieldsValue.startTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
          );
          fieldsValue.endTime = formatDate(new Date(nowYear, nowMonth, nowDay));
          // delete fieldsValue.totalPeriodType;
        }
        if (fieldsValue.totalPeriodType === 4) {
          //本月
          fieldsValue.startTime = formatDate(new Date(nowYear, nowMonth, 1));
          fieldsValue.endTime = formatDate(new Date(nowYear, nowMonth, nowDay));
          // delete fieldsValue.totalPeriodType;
        }
        if (fieldsValue.totalPeriodType === 5) {
          //上周
          fieldsValue.startTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6)
          );
          fieldsValue.endTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek)
          );
          // delete fieldsValue.totalPeriodType;
        }
        if (fieldsValue.totalPeriodType === 8) {
          //上月
          fieldsValue.startTime = formatDate(
            new Date(
              new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate(
                1
              )
            )
          );
          fieldsValue.endTime = formatDate(new Date(new Date().setDate(0)));
          // delete fieldsValue.totalPeriodType;
        }
      } else {
        // 更多筛选的数据
        if (filterTime.rangeTime) {
          fieldsValue.startTime = moment(filterTime.rangeTime[0]).format(
            "YYYYMMDD"
          );
          fieldsValue.endTime = moment(filterTime.rangeTime[1]).format(
            "YYYYMMDD"
          );
          delete fieldsValue.rangeTime;
          // delete fieldsValue.totalPeriodType;
        }
        if (filterTime.totalPeriodType === 2) {
          //本周
          fieldsValue.startTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
          );
          fieldsValue.endTime = formatDate(new Date(nowYear, nowMonth, nowDay));
          // delete fieldsValue.totalPeriodType;
        }
        if (filterTime.totalPeriodType === 4) {
          //本月
          fieldsValue.startTime = formatDate(new Date(nowYear, nowMonth, 1));
          fieldsValue.endTime = formatDate(new Date(nowYear, nowMonth, nowDay));
          // delete fieldsValue.totalPeriodType;
        }
        if (filterTime.totalPeriodType === 5) {
          //上周
          fieldsValue.startTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6)
          );
          fieldsValue.endTime = formatDate(
            new Date(nowYear, nowMonth, nowDay - nowDayOfWeek)
          );
          // delete fieldsValue.totalPeriodType;
        }
        if (filterTime.totalPeriodType === 8) {
          //上月
          fieldsValue.startTime = formatDate(
            new Date(
              new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate(
                1
              )
            )
          );
          fieldsValue.endTime = formatDate(new Date(new Date().setDate(0)));
          // delete fieldsValue.totalPeriodType;
        }
      }
      const conditions = [];
      if (currentSearchMode == "1") {
        //非更多筛选
        if (fieldsValue.vin) {
          conditions.push({
            columnName: "vin",
            columnType: 1,
            filter: fieldsValue.vin ? "1" : undefined,
            startVal: fieldsValue.vin,
            endVal: undefined,
            filterType: "1",
          });
        }
        if (fieldsValue.orgId) {
          conditions.push({
            columnName: "company_name",
            filter: fieldsValue.orgId ? "9" : undefined,
            startVal: fieldsValue.orgId,
            endVal: undefined,
            filterType: "1",
          });
        }
        if (fieldsValue.creditType) {
          conditions.push({
            columnName: "credit_type",
            filter: fieldsValue.creditType ? "9" : undefined,
            startVal: fieldsValue.creditType,
            endVal: undefined,
            filterType: "1",
          });
        }
        if (typeof fieldsValue.riskStatus !== "undefined") {
          conditions.push({
            columnName: "risk_status",
            filter: fieldsValue.riskStatus ? "9" : undefined,
            startVal: fieldsValue.riskStatus === 0 ? 0 : fieldsValue.riskStatus,
            endVal: undefined,
            filterType: "1",
          });
        }

        fieldsValue.conditions = conditions;
      } else {
        fieldsValue.conditions = fieldColumns;
      }
      // if(params){
      //   fieldsValue.conditions = params;
      // }
      delete fieldsValue.vin;
      delete fieldsValue.orgId;
      delete fieldsValue.riskStatus;
      (fieldsValue.businessCode = "mileage"),
        dispatch({
          type: "mileage/queryList",
          payload: {
            url: "/mscreditbusiness/vehicle/mileage/report/page",
            ...fieldsValue,
            curPage: 1,
            pageSize: 10,
          },
        });
      this.setState({ formValues: { ...fieldsValue } });
    });
  };

  disabledDate = (current) => {
    const { dates } = this.state;
    if (dates && dates.length > 0) {
      const tooLate = dates[0] && current.diff(dates[0], "days") > 31;
      const tooEarly = dates[1] && dates[1].diff(current, "days") > 31;
      return (
        (current &&
          current < moment().add(-1, "years").add(-1, "days").endOf("day")) ||
        current > moment().add(-1, "days").endOf("day") ||
        tooLate ||
        tooEarly
      );
    }
    return (
      (current &&
        current < moment().add(-1, "years").add(-1, "days").endOf("day")) ||
      current > moment().add(-1, "days").endOf("day")
    );
  };

  onOpenChange = (open) => {
    if (open) {
      this.setState({ dates: [] });
    }
  };

  onCalendarChange = (dates) => {
    this.setState({ dates });
  };

  exportMonitorVehicle = () => {
    const { dispatch } = this.props;
    const { formValues, pageObj,fieldColumns, currentSearchMode } = this.state;
    dispatch({
      type: "mileage/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/mileage/downloadTask",
        ...formValues,
        curPage: pageObj.current,
        pageSize: pageObj.pageSize,
      }, //页码为固定值，与列表查询接口共用一个VO，不传页码会出现空指针异常
      callback: (response) => {
        if (response.statusCode === "0") {
          message.success("操作成功，请点击【导出任务】按钮查看导出进度！");
        } 
        // else if (response.statusCode === "12097023") {
        //   message.warning(
        //     "您有一个下载任务正在执行，请点击导出任务按钮查看导出进度！"
        //   );
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };

  onRadioChange = (info) => {
    this.props.form.resetFields(["rangeTime"]);
    if (info && info.target) {
      if (info.target.value === 0) {
        this.setState({
          dateDisable: false,
        });
      } else {
        this.setState({
          dateDisable: true,
        });
      }
    }
  };

  openExportTaskModal = () => {
    this.exportTaskRef.openModal();
    this.exportTaskRef.initData();
  };

  checkRangeType = (rule, value, callback) => {
    const rangeType = this.props.form.getFieldValue("totalPeriodType");
    if (rangeType === 0 && !value) {
      callback("请输入统计周期具体日期！");
      return;
    }
    callback();
  };

  handleTableChange = (page) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      curPage: page.current,
      pageSize: page.pageSize,
      ...formValues,
    };
    this.setState({
      pageObj: {
        curPage: page.current,
        pageSize: page.pageSize,
      },
    });
    dispatch({
      type: "mileage/queryList",
          payload: {
            url: "/mscreditbusiness/vehicle/mileage/report/page",
        ...params,
      },
      callback: (response) => {
        this.setState({ initFlag: true });
      },
    });
  };
  getList = () => {
    const { dispatch } = this.props;
    const { formValues, pageObj } = this.state;
    dispatch({
      type: "mileage/queryList",
          payload: {
            url: "/mscreditbusiness/vehicle/mileage/report/page",
        curPage: 1,
        pageSize: 10,
        ...formValues,
      },
    });
  };
  // TBOX唤醒
  tboxWakeUp = (vin) => {
    this.setState({
      tboxRouseloading: true,
    });
    this.props.dispatch({
      type: "mileage/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/tbox/wake",
        vin: vin,
        businessCode: "credit-mileage-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("已经给该车辆发送远程唤醒指令");
          let tboxRouseCount = 35;
          let tboxRouseSearchCount = 3;
          this.timer = setInterval(() => {
            tboxRouseCount--;
            this.setState({ tboxRouseCount });
            //请求详情接口
            if (tboxRouseCount <= 0) {
              this.setState({
                tboxRouseloading: false,
                tboxRouseCount: 35,
              });
              clearInterval(this.timer);
              message.error("TBOX没有被成功唤醒");
            }
          }, 1000);

          this.timer2 = setInterval(() => {
            tboxRouseSearchCount--;
            //请求详情接口
            this.props.dispatch({
              type: "creditCar/postDataWithRes",
              payload: {
                url: "/mscreditbusiness/vehicle/tbox/wake/result",
                vin: vin,
              },
              callback: (response) => {
                if (response && response.statusCode == "0") {
                  if (response.data) {
                    message.success("TBOX被成功唤醒");
                    this.handleFlushPage();
                    clearInterval(this.timer2);
                    clearInterval(this.timer);
                    this.setState({
                      tboxRouseloading: false,
                      tboxRouseCount: 35,
                    });
                  }
                } else {
                  // message.error(response.statusMessage);
                }
              },
            });

            if (tboxRouseSearchCount <= 0 || tboxRouseCount <= 0) {
              clearInterval(this.timer2);
            }
          }, 10000);
        } else {
          // message.error(response.statusMessage);
          this.setState({
            tboxRouseloading: false,
            tboxRouseCount: 35,
          });
        }
      },
    });
  };
  componentWillUnmount() {
    clearInterval(this.timer2);
    clearInterval(this.timer);
  }
  onRoleRef = (ref) => {
    this.Field = ref;
  };
  changeriskStatusModalVisible = (flag) => {
    if (flag) {
      this.setState({
        riskStatusModalVisible: false,
      });
    } else {
      this.setState({
        riskStatusModalVisible: false,
      });
    }
  };
  //点击车辆风控状态
  handleriskStatus(text, record) {
    console.log(record.vin, "recordrecordrecord");
    this.setState({
      riskvin: record.vin,
      riskStatusModalVisible: true,
    });
  }
  render() {
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    const isExport = permissions.includes(pathname + '/' + 'mileage_export');
    const isTask = permissions.includes(pathname + '/' + 'mileage_task');
    const {form: { getFieldDecorator }} = this.props;
    const {
      mileage: {
         loading,
         rows,
         pagination,
       },
       dispatch,
     } = this.props;
    const {
      formValues,
      dateDisable,
      initFlag,
      tboxRouseloading,
      tboxRouseCount,
      fieldList,
      tableColumns,
      visible,
      checked,
      columns,
      orgList,
      creditTypeOptions,
      pageObj
    } = this.state;
    // pageObj = pagination;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>
          共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条
        </span>
      ),
    };
    const drivingMileageTotalBtn = {
      title: "统计周期内的行驶里程",
      dataIndex: "drivingMileageTotal",
      key: "drivingMileageTotal",
    };
    const tboxBtn = {
      title: "操作",
      dataIndex: "操作",
      fixed: "right",
      align: "center",
      filterDropdown: <div></div>,
      filterIcon: (
        <Tooltip placement="top" title="筛选">
          <SettingOutlined 
            type="setting"
            style={{ marginLeft: 1 }}
            onClick={() => this.openFieldModal()}
          />
        </Tooltip>
      ),
      render: (text, record) => {
        const btns = [
          {
            title: "TBOX唤醒",
            key: "action",
            Popconfirm: true,
            message: "是否要对TBOX进行远程唤醒？",
            onConfirm: () => this.tboxWakeUp.bind(this)(record?.vin),
          },
        ];

        if (record.tboxLostDays >= 1) {
          return (
            <PateoAuthButtons
              authStr="mileage"
              btns={btns}
            />
          );
        } else {
          return "";
        }
      },
    };
    return (
      <Spin
        spinning={tboxRouseloading}
        size="large"
        tip={`Loading(${tboxRouseCount})s`}
      >
        <div>
           <div className={styles.pateoSearch}>
                  <Form onSubmit={this.handleSearch}>
                     <Row gutter={24}>
                       <Col span={8}>
                  
                       <FormItem key={"vin"} label={"VIN号"}>
                          {getFieldDecorator("vin")(
                            <Input 
                                placeholder="请填写VIN号" />
                          )}
                        </FormItem>
                       
                        </Col>
                        <Col span={8}>
                        <FormItem key={"orgId"} label={"车辆所属公司"}>
                          {getFieldDecorator("orgId")(
                            <Select
                              placeholder="请选择"
                              optionFilterProp="children"
                              allowClear={true}
                              showSearch
                              getPopupContainer={(triggerNode) =>

                                triggerNode.parentNode
                              }
                            >
                              {G.transferOption(orgList, ["sid", "name"])}
                            </Select>
                          )}
                        </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem key={"riskStatus"} label={"车辆风控状态"}>
                          {getFieldDecorator("riskStatus")(
                            <Select
                              placeholder="请选择"
                              optionFilterProp="children"
                              allowClear={true}
                            >
                              <Option value={"0"}>正常行驶</Option>
                              <Option value={"1"}>锁车</Option>
                              <Option value={"2"}>跛行</Option>
                            </Select>
                          )}
                        </FormItem>
                        </Col>
                  </Row>
                  <Row gutter={24}>
                    <Col span={8}>
                        <FormItem key={"creditType"} label={"授信类型"}>
                          {getFieldDecorator("creditType")(
                            <Select
                              placeholder="请选择"
                              optionFilterProp="children"
                              allowClear={true}
                            >
                             {transferOption(this.state.creditTypeOptions, ["value","label"])}
                            </Select>
                          )}
                        </FormItem>
                      </Col>  
                      <Col span={10}>
                        <FormItem key={"totalPeriodType"} label={"统计周期"}>
                          {getFieldDecorator("totalPeriodType", {
                            initialValue: 2,
                          })(
                            <RadioGroup onChange={this.onRadioChange}>
                              <Radio value={2}>本周</Radio>
                              <Radio value={4}>本月</Radio>
                              <Radio value={5}>上周</Radio>
                              <Radio value={8}>上月</Radio>
                              <Radio value={0}>具体日期</Radio>
                            </RadioGroup>
                          )}
                        </FormItem>
                        </Col>  
                        <Col span={6}>
                        <FormItem key={"rangeTime"}>
                          {getFieldDecorator("rangeTime", {
                            rules: [{ validator: this.checkRangeType }],
                          })(
                            <RangePicker
                              disabled={dateDisable}
                              disabledDate={this.disabledDate}
                              placeholder={["开始日期", "结束日期"]}
                              allowClear
                              style={{ width: "100%", marginLeft: "-25%" }}
                              format="YYYY-MM-DD"
                              onCalendarChange={this.onCalendarChange}
                              onOpenChange={this.onOpenChange}
                              getCalendarContainer={(trigger) =>
                                trigger.parentNode
                              }
                            />
                          )}
                        </FormItem>
                        </Col>
                    </Row>  
                  </Form>
                   
                   <div className={styles.searchBtn}>
                          <Button
                            style={{ marginRight: "10px" }}
                            onClick={(e) => this.moreFilter(e)}
                          >
                            更多筛选条件
                          </Button>
                          <Button
                            type="primary"
                            onClick={() => this.handleSearchFor()}
                          >
                            查询
                          </Button>
                          <Button
                            style={{ marginLeft: 8 }}
                            onClick={this.handleFormReset}
                          >
                            重置
                          </Button>
                    </div>
                </div>
                <div className={styles.pateoBtns}>
                  {isExport ? (
                    <Button
                      type="primary"
                      style={{ marginBottom: 10, marginRight: 10 }}
                      onClick={() => this.exportMonitorVehicle()}
                    >
                      导出列表
                    </Button>
                  ) : null}
                  {isTask ? (
                    <Button
                      type="primary"
                      style={{ marginBottom: 10, marginRight: 10 }}
                      onClick={() => this.openExportTaskModal()}
                    >
                      导出任务
                    </Button>
                  ) : null}
                   </div>
                  <Card bordered={false} style={{ marginTop: 10 }}>
                  <Table
                    rowKey={(record) => record.vin}
                    columns={columns.concat(
                      [drivingMileageTotalBtn],
                      [tboxBtn]
                    )}
                    dataSource={ rows || []}
                    formValues={this.state.formValues}
                    pagination={paginationProps}
                    onChange={this.handleTableChange}
                    scroll={{ x: "max-content" }}
                  />
                 </Card>
                  <ExportTaskModal
                    onRef={(ref) => (this.exportTaskRef = ref)}
                    dispatch={this.props.dispatch}
                  />
                  {visible && (
                    <FieldModal
                      //  onRef={this.onRef}
                      modalVisible={visible}
                      dispatch={this.props.dispatch}
                      fieldList={fieldList}
                      filterColumns={this.filterColumns}
                      checked={checked}
                      closeModal={() => {
                        this.setState({ visible: false });
                      }}
                    />
                  )}
                  <SearchAdtional
                    onRef={(ref) => (this.SearchAdtionalRef = ref)} // ref赋值
                    SearchAdtionalOptions={this.state.fieldMore} // 可选字段
                    specialData={this.state.specialData} // 特殊字段
                    fieldName="mileage"
                    handleSubmit={(columns) => {
                      // 点击确认搜索
                      this.setState(
                        {
                          fieldColumns: columns,
                          currentSearchMode: "2",
                        },
                        () => {
                          this.handleSearch();
                        }
                      );
                    }}
                    getStatisticalCycle={this.getStatisticalCycle}
                  ></SearchAdtional>
                  {this.state.riskStatusModalVisible ? (
                    <RiskStatusModal
                      changeriskStatusModalVisible={
                        this.changeriskStatusModalVisible
                      }
                      riskvin={this.state.riskvin}
                    />
                  ) : null}
            </div>
      </Spin>
    );
  }
}
